const cloud = require('wx-server-sdk');

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        // 请求参数
        let {
            pageNum = 1, pageSize = 10, conditions,
        } = event.data

        if (typeof conditions == "string") {
            // 未传递筛选条件时 conditions会默认等于"1"
            conditions = {}
        }
        // 构建查询条件
        let query = db.collection('agentCouponRecord')

        // 时间范围筛选
        if (conditions.startTime && conditions.endTime) {
            conditions = {
                ...conditions,
                createTime: db.command.gte(new Date(conditions.startTime)) // 大于等于开始时间
                    .and(db.command.lte(new Date(conditions.endTime))) // 小于等于结束时间
            }
            delete conditions.startTime
            delete conditions.endTime
        }

        // 有效周期筛选
        if (conditions.effectiveStartTime && conditions.effectiveEndTime) {
            conditions = {
                ...conditions,
                effectiveStartTime: db.command.gte(conditions.effectiveStartTime),
                effectiveEndTime: db.command.lte(conditions.effectiveEndTime),
            }
        }

        query = query.where(conditions) // 添加筛选条件
        query = query.orderBy('createTime', 'desc') // 排序

        const skip = (pageNum - 1) * pageSize // 计算跳过的记录数

        // 查询数据
        const data = await query
            .skip(skip)
            .limit(pageSize)
            .get()

        // 获取总数
        const countResult = await query.count()

        // 返回查询结果
        return {
            code: 200,
            msg: "操作成功",
            data: data.data,
            total: countResult.total,
            totalPages: Math.ceil(countResult.total / pageSize),
        }
    } catch (err) {
        return {
            code: 500,
            message: err.message
        }
    }
};